﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using Dong8Triggers;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.InteropServices;
using System.IO;
using System.Web.Script.Serialization;
using ETS_FinancialData_sync_toolsForServer;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
namespace ETS_FinancialData_sync_tools
{
    public partial class server : Form
    {
        public server()
        {
            InitializeComponent();
            Login.OnPacUpdateEvent += apendText;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //string table = @"sid,cardno,cname,sex,mem_status,mem_type,checkin_date,checkin_time,operator,checkin_status,if_towel,if_keyring,keyno,if_returnkey,checkouttime,memo,color,memiden,memid,workshop,expendcard,deposit,guesttype,issuecard,lockstatus,clubcode,posflag,fEntityNo,FClub,Fpcno,fcreatedate,fmodifydate,fUserNo,n_last,ifdown,fmp,ifinshoes,ifshoes,shoesdate1,fbillNo,fmpdate,shoesdate2,ifoutshoes,fgphzs,fbphzs,fsalempdttime,ifcusttype,fje,fqry,fcusttdno,fbillNosub,city_id,fmpsttdate,fmpenddate,fmpusermin,fmpdaycount,shoesdate4,fmpjeall,fyjjeall,finje,ftime_mode,timestampflag";
            //string[] arr = table.Split(',');
            //string result = string.Empty;
            //foreach (string filed in arr)
            //{
            //    result += "public object "+filed+" { get; set; }\n";
            //    //result += "if (oldReader == null || reader[\"" + filed + "\"].ToString() != oldReader[\"" + filed + "\"].ToString()) { this.map[\"" + filed + "\"] = reader[\"" + filed + "\"].ToString(); }\n";
            //}
            //MessageBox.Show(result);
            code();
        }
        public string code_string;
        public string code()
        {
            string[] table = new string[4];
            table[0] = "pos_sales";
            table[1] = "sys_payment";
            table[2] = "pos_bill_payment";
            table[3] = "fitness_checkin";
            string[] filedArr = new string[4];
            filedArr[0] = "'saleid','billcode','grand_billcode','rec_status','sale_status','pay_status','sale_type','billshop','saleshop','payshop','produceshop','saledate','saletime','closedate','paydate','userid','itemcode','itemname1','itemname2','itemspec','saleprice','quantity','saletotal','discountpercent','discounttotal','gratuitypercent','gratuitytotal','rebatetotal','taxpercent','taxtotal','totalpayable','saleweight','stockprice','stockqty','modifier_memo','serverno','if_discount','if_gratuity','sale_prop','if_revenue','if_generate','if_other','if_invoice','closemethod','paymethod','checkin_id','orderno','seatno','printno','otherid','if_import','if_tax','pricemethod','sale_kinds','parent_kinds','sale_category','parent_category','sale_special','parent_special','stat_code','paymentid','fit_paymentid','payflag','itemid','autocdflag','otherflag','complimentary_flag','modifier','reason','kitchen_type','seat_no','is_meal','is_backup','meal_id','meal_type','is_inv','is_addtion','club_id','holidaymethod','clubcode','sttime','endtime','fcount_hh','fcount_mm','fcditemno','Fpcno','fclub','fEntityNo','fit_saleid','fcreatedate','fmodifydate','fUserNo','n_last','ifdown','xh','dzxh','dj_cb','je_cb','bm_ck','is_check','walkcust_ftype','keyno','memno','Fremark','deposit','fcusttdno','fbillNosub','disccode','spandhyacc','ch_printflag','accuserid','fdayandhousr','fmpdaycount','zbcardno','v_artno','Fmp_m_id','acc_clubkinds1','acc_clubkinds2','acc_clubkinds3'";
            filedArr[1] = "'code','name_c','if_efficieny','type','parent_code','if_sat','name_e','if_account','account_code','memo','money_type','payment_type','bank_service','parent_type','detail_type','type_workshop','type_code','touch_disp','fifrepacc','Fclub'";
            filedArr[2] = "'paymentid','billcode','rec_status','pay_status','paymethod','payparent','payamount','payforeign','payshop','paydate','payflag','payrate','payfamt','paychanges','paycardno','ExpiryDate','paysysid','payname','userid','shiftno','if_invoice','if_revenue','payno','paymemo','paytype','memid','clubcode','fit_paymentid','fEntityNo','FClub','Fpcno','fcreatedate','fmodifydate','fUserNo','n_last','ifdown','syscode','paycode','sale_kinds','sale_category','sale_special','fifrepacc','fifdhyhpay'";
            filedArr[3] = "'sid','cardno','cname','sex','mem_status','mem_type','checkin_date','checkin_time','operator','checkin_status','if_towel','if_keyring','keyno','if_returnkey','checkouttime','memo','color','memiden','memid','workshop','expendcard','deposit','guesttype','issuecard','lockstatus','clubcode','posflag','fEntityNo','FClub','Fpcno','fcreatedate','fmodifydate','fUserNo','n_last','ifdown','fmp','ifinshoes','ifshoes','shoesdate1','fbillNo','fmpdate','shoesdate2','ifoutshoes','fgphzs','fbphzs','fsalempdttime','ifcusttype','fje','fqry','fcusttdno','fbillNosub','city_id','fmpsttdate','fmpenddate','fmpusermin','fmpdaycount','shoesdate4','fmpjeall','fyjjeall','finje','ftime_mode'";
            string sql;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < table.Length; i++)
            {
                sb.Length = 0;
                //MessageBox.Show(table[i]);
                sql = @"SELECT
                col.name AS 列名,
                typ.name as 数据类型,
                col.max_length AS 占用字节数,
                col.precision AS 数字长度,
                col.scale AS 小数位数,
                col.is_nullable AS 是否允许非空,
                col.is_identity AS 是否自增,
                case when exists 
                ( SELECT 1 
                FROM 
                sys.indexes idx 
                join sys.index_columns idxCol 
                on (idx.object_id = idxCol.object_id)
                WHERE
                idx.object_id = col.object_id
                AND idxCol.index_column_id = col.column_id
                AND idx.is_primary_key = 1
                ) THEN 1 ELSE 0 END AS 是否是主键,
                isnull(prop.[value],'-') AS 说明
                FROM
                sys.columns col left join sys.types typ 
                on (col.system_type_id = typ.system_type_id)
                left join sys.extended_properties prop
                on (col.object_id = prop.major_id AND prop.minor_id = col.column_id)
                WHERE
                col.object_id =
                (SELECT object_id FROM sys.tables WHERE name = '" + table[i] + "')";
                sql +=
                @"and col.name in(" + filedArr[i] +
                @")
                and typ.name not like '%TYPE' and typ.name not like '%name'
                ORDER BY 列名
                ";
                SqlConnection conn = new SqlConnection("Server=.\\sql2008;Integrated Security=SSPI;database=taiyuan");
                conn.Open();
                SqlCommand command = new SqlCommand(sql, conn);
                SqlDataReader reader = command.ExecuteReader();

                string type;
                string filed;
                while (reader.Read())
                {
                    //MessageBox.Show(reader[1].ToString());
                    type = reader[1].ToString();
                    filed = reader[0].ToString();
                    if (type.Contains("ar"))
                    {
                        //sb.AppendLine("t."+filed+" = dr[\"" + filed + "\"].ToString();");
                        //sb.AppendLine("if (oldReader == null || reader[\"" + filed + "\"].ToString() != oldReader[\"" + filed + "\"].ToString()) { this.map[\"" + filed + "\"] = reader[\"" + filed + "\"].ToString(); }");
                        //sb.AppendLine("sql += \"'\"+dict[\"" + filed + "\"] + \"',\";");
                        sb.AppendLine("if (dict.ContainsKey(\"" + filed + "\")){builder.Append(\"," + filed + "='\").Append(dict[\"" + filed + "\"]).Append(\"'\");}");
                    }
                    else if (type.Contains("time"))
                    {
                        // sb.AppendLine("t." + filed + " = dr[\"" + filed + "\"].ToString();");
                        //sb.AppendLine("if (oldReader == null || reader[\"" + filed + "\"].ToString() != oldReader[\"" + filed + "\"].ToString()) { this.map[\"" + filed + "\"] = CLRTriggers.getDateTimeString(reader,\"" + filed + "\"); }");
                       // sb.AppendLine("sql += \"'\"+dict[\"" + filed + "\"] + \"',\";");
                        sb.AppendLine("if (dict.ContainsKey(\"" + filed + "\")){builder.Append(\"," + filed + "='\").Append(dict[\"" + filed + "\"]).Append(\"'\");}");
                    }
                    else if (type.Contains("dec") || type.Contains("num") || type.Contains("int"))
                    {

                        //sb.AppendLine("t." + filed + " = getDoubleString(dr, \""+filed+"\");");
                        //sb.AppendLine("if (oldReader == null || reader[\"" + filed + "\"].ToString() != oldReader[\"" + filed + "\"].ToString()) { this.map[\"" + filed + "\"] = CLRTriggers.getDoubleString(reader,\"" + filed + "\"); }");
                        //sb.AppendLine("sql += toNull(dict[\"" + filed + "\"]) + \",\";");
                        sb.AppendLine("if (dict.ContainsKey(\"" + filed + "\")){builder.Append(\"," + filed + "=\").Append(dict[\"" + filed + "\"]);}");
                    }
                    else
                    {
                        //sb.AppendLine("t." + filed + " = getIntString(dr, \"" + filed + "\");");
                        //sb.AppendLine("if (oldReader == null || reader[\"" + filed + "\"].ToString() != oldReader[\"" + filed + "\"].ToString()) { this.map[\"" + filed + "\"] = CLRTriggers.getIntString(reader,\"" + filed + "\"); }");
                        //sb.AppendLine("sql += \"'\"+dict[\"" + filed + "\"] + \"',\";");
                        sb.AppendLine("if (dict.ContainsKey(\"" + filed + "\")){builder.Append(\"," + filed + "=\").Append(dict[\"" + filed + "\"]);}");
                    }
                }

                conn.Close();
                richTextBox1.Clear();
                richTextBox1.Text = sb.ToString();
                MessageBox.Show(richTextBox1.Text);
            }


            return sb.ToString();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                helper h = new helper();
                h.getsqlconn();
                DbHelper.getsqlconn();
                string connString = h.Sqlconn;
                connString = connString.Remove(connString.LastIndexOf("pwd"), connString.Length - connString.LastIndexOf("pwd")) + "******";
                label1.Text = "连接参数:" + connString;
                txtPort.Text = h.ContentValue("Connection", "port");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            setup s = new setup();
            s.ShowDialog();
        }
        private string ServerIp;//服务器地址
        private int port;//服务器端口
        Thread myThread;
        Socket socket;
        /// <summary>
        /// 是否正常退出所有接收线程
        /// </summary>
        bool isNormalExit = false;

        private void btnConnect_Click(object sender, EventArgs e)
        {

            TcpServer tcpServer = new TcpServer();
            tcpServer.Start();
            apendText("服务器启动成功");
            Console.WriteLine("服务器启动成功，按任意键退出.");

            //myThread = new Thread(ListenClientConnet);
            //myThread.Start();
        }


        //private void onPacUpdateEvent(string text)
        //{
        //    /*在这里调用控件的异步更新函数。*/
        //    Action<string> actionDelegate = (x) =>
        //    {
        //        if (this.richTextBox1.Text.Length > 20000)
        //        {
        //            this.richTextBox1.Text = this.richTextBox1.Text.Substring(20000, this.richTextBox1.Text.Length - 20000);
        //        }
        //        this.richTextBox1.AppendText("\n\r" + text);
        //        this.richTextBox1.ScrollToCaret();
        //    };
        //    this.richTextBox1.Invoke(actionDelegate, "\n\r" + text);
        //}

        //委托 
        public delegate void appendTextToRichtextBox(string text);
        public void apendText(string text)
        {
            Action<string> actionDelegate = (x) =>
            {
                if (this.richTextBox1.Text.Length > 20000)
                {
                    this.richTextBox1.Text = this.richTextBox1.Text.Substring(20000, this.richTextBox1.Text.Length - 20000);
                }
                this.richTextBox1.AppendText("\n\r" + text);
                this.richTextBox1.ScrollToCaret();
            };
            this.richTextBox1.Invoke(actionDelegate, "\n\r" + text);
        }

        private void ListenClientConnet()
        {
            //创建一个新的Socket,这里我们使用最常用的基于TCP的Stream Socket（流式套接字）
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //将该socket绑定到主机上面的某个端口
            //方法参考：http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.bind.aspx
            socket.Bind(new IPEndPoint(IPAddress.Any, 4530));

            //启动监听，并且设置一个最大的队列长度
            //方法参考：http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.listen(v=VS.100).aspx
            socket.Listen(4);

            //开始接受客户端连接请求
            //方法参考：http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.beginaccept.aspx
            socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
            apendText(string.Format("Server is ready!"));

        }
        public int clientConectCount = 0;
        public void ClientAccepted(IAsyncResult ar)
        {

            var socket = ar.AsyncState as Socket;

            //这就是客户端的Socket实例，我们后续可以将其保存起来
            var client = socket.EndAccept(ar);

            //给客户端发送一个欢迎消息
            client.Send(Encoding.Unicode.GetBytes("Hi there, I accept you request at " + DateTime.Now.ToString()));
            apendText("Hi there, I accept you request at " + DateTime.Now.ToString());
            int i = 0;

            clientConectCount++;
            //实现每隔两秒钟给服务器发一个消息
            //这里我们使用了一个定时器
            var timer = new System.Timers.Timer();
            timer.Interval = 2000D;
            timer.Enabled = true;
            timer.Elapsed += (o, a) =>
            {

                //检测客户端Socket的状态
                if (client.Connected)
                {
                    try
                    {
                        client.Send(Encoding.Unicode.GetBytes("Message from server at " + DateTime.Now.ToString() + "to client!"));
                        apendText("Message from server at " + DateTime.Now.ToString());

                    }
                    catch (SocketException ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                else
                {
                    clientConectCount--;
                    timer.Stop();
                    timer.Enabled = false;
                    Console.WriteLine("Client is disconnected, the timer is stop.");
                    apendText("Client is disconnected, the timer is stop.");

                }
                apendText("当前连接数: " + clientConectCount);
            };
            timer.Start();


            //接收客户端的消息(这个和在客户端实现的方式是一样的）
            client.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);

            //准备接受下一个客户端请求
            socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
        }

        byte[] bytes = new byte[1024];
        public void ReceiveMessage(IAsyncResult ar)
        {
            while (clientConectCount > 0)
            {
                StringBuilder buffer = new StringBuilder();
                try
                {

                    var socket = ar.AsyncState as Socket;
                    buffer.Remove(0, buffer.Length);
                    while (clientConectCount > 0)
                    {
                        //var length = socket.EndReceive(ar);
                        int len1 = socket.Receive(bytes);
                        //读取出来消息内容
                        string message = Encoding.Unicode.GetString(bytes, 0, len1);
                        //message = Regex.Unescape(message);
                        //System.Text.UnicodeEncoding encodingUNICODE = new System.Text.UnicodeEncoding();
                        //message=encodingUNICODE.GetString(new UnicodeEncoding().GetBytes(message));
                        //if (!message.EndsWith("~!@#$%"))
                        //{
                        //    continue;
                        //}
                        //buffer.Append(message.Replace("~!@#$%", ""));
                        buffer.Append(message);
                        if (message.EndsWith("~!@#$%"))
                        {
                            break;
                        }

                    }
                    //显示消息
                    apendText(buffer.ToString().Replace("~!@#$%", ""));

                    string test = buffer.ToString();
                    string r = test.Replace("]", "");
                    int num = (test.Length - r.Length) / 2;
                    if (num > 1)
                    {
                        MessageBox.Show(test);
                    }
                    //将json还原为一个同步消息列表
                    List<Dictionary<string, Object>> list = JsonConvert.DeserializeObject<List<Dictionary<string, Object>>>(buffer.ToString().Replace("~!@#$%", ""));

                    //循环读取同步消息
                    List<Dictionary<string, Object>> returnList = new List<Dictionary<string, Object>>();
                    foreach (Dictionary<string, Object> obj in list)
                    {
                        Dictionary<string, Object> returnDict = null;

                        if (obj["data_type"].ToString() == "pos_bills")
                        {
                            returnDict = DbHelper.handle_pos_bills(obj);
                            returnDict["ver"] = DbHelper.Ver;
                            returnList.Add(returnDict);
                        }
                        else if (obj["data_type"].ToString() == "pos_sales")
                        {
                            returnDict = DbHelper.handle_pos_sales(obj);
                            returnDict["ver"] = DbHelper.Ver;
                            returnList.Add(returnDict);
                        }
                    }
                    String returnMsg = JsonConvert.SerializeObject(returnList);
                    socket.Send(Encoding.Unicode.GetBytes(returnMsg + "~!@#$%"));
                    apendText(returnMsg);
                    buffer.Remove(0, buffer.Length);
                }
                catch (Exception ex)
                {

                    DbHelper.saveErrLog(ex.Message + "\n\r" + ex.StackTrace + "\n\r" + buffer.ToString(), "ex");
                    //Console.WriteLine(ex.Message);
                    buffer.Remove(0, buffer.Length);
                }
            }
        }

        /// <summary>
        /// 数据访问层
        /// </summary>
        public class DbHelper
        {

            /// <summary>
            /// 判断传入的值是否为空
            /// </summary>
            /// <param name="o"></param>
            /// <returns></returns>
            public static string ifIsNull(Object o)
            {
                String rtn = null;
                if (o != null && o.ToString().Length > 0)
                {
                    rtn = "'" + Convert.ToDateTime(o).ToString() + "'";
                }
                else
                {
                    rtn = "null";
                }
                return rtn;
            }

            public static string toNull(object value)
            {
                string retunValue = null;
                if (value.ToString().Length == 0)
                {
                    retunValue = "null";
                }
                else
                {
                    retunValue = value.ToString();
                }
                return retunValue;
            }

            #region //处理账单主表的方法
            /// <summary>
            /// 处理账单主表的方法
            /// </summary>
            /// <param name="dict"></param>
            /// <returns></returns>
            public static Dictionary<string, Object> handle_pos_bills(Dictionary<string, Object> dict)
            {


                Dictionary<string, Object> returnDict = new Dictionary<string, Object>();
                //TODO: 下面要补上数据库操作的代码
                string sql = "";
                try
                {

                    if (ifSync_idExist("select COUNT(*) from t_sync where sync_id='" + dict["sync_id"] + "'") > 0)
                    {
                        returnDict["sync_id"] = dict["sync_id"];
                        returnDict["status"] = 1;
                        returnDict["remark"] = "这个sync_id已经处理过啦。";
                        return returnDict;
                    }

                    StringBuilder builder = new StringBuilder(400);

                    if (Convert.ToInt32(dict["sync_type"]) == 0)
                    {
                        sql = "insert into pos_bills(accuserid,bill_status,billcode,billdate,billshop,billtotal,billtype,bm_ck,cardbalance,cardno,ch_payno,checker,checkin_id,closedate,closeshift,closetime,closeuserid,club_id,clubcode,dailysno,depositall,discountpercent,discounttotal,dzxh,endtime,f_paykind,fbillnohbaccno,fcditemno,fclub,fcount_hh,fcount_mm,fcreatedate,fcusttdno,fEntityNo,fhbbillflash,finmpyj,fmodifydate,Fpcno,fRemark,fRemarkdoc,fUserNo,fydbillno,generateflag,grand_billcode,gratuitypercent,gratuitytotal,guest_identity,ifdown,invoiceflag,invoiceno,is_check,keyno,lockstatus,memid,memno,memsid,modify,modifytime,n_last,name,noofguest,opentime,openuserid,otherstatus,parentshop,pay_status,paycode,paydesp,payflag,paymethod,payshop,periodno,printno,quitydje,rebatetotal,rec_status,reception,rq_check,saleid,saleshop,saletype,sequence,serverno,sex,shiftno,sttime,syscode,tableno,tableno_ext,taxpercent,taxtotal,tipstotal,totalpayable,ydallje,zb_bm_ck)";
                        sql += " values(";
                        sql += "'" + dict["accuserid"] + "',";
                        sql += toNull(dict["bill_status"]) + ",";
                        sql += "'" + dict["billcode"] + "123123',";
                        sql += "'" + dict["billdate"] + "',";
                        sql += "'" + dict["billshop"] + "',";
                        sql += toNull(dict["billtotal"]) + ",";
                        sql += toNull(dict["billtype"]) + ",";
                        sql += "'" + dict["bm_ck"] + "',";
                        sql += toNull(dict["cardbalance"]) + ",";
                        sql += "'" + dict["cardno"] + "',";
                        sql += "'" + dict["ch_payno"] + "',";
                        sql += "'" + dict["checker"] + "',";
                        sql += "'" + dict["checkin_id"] + "',";
                        sql += "'" + dict["closedate"] + "',";
                        sql += "'" + dict["closeshift"] + "',";
                        sql += "'" + dict["closetime"] + "',";
                        sql += "'" + dict["closeuserid"] + "',";
                        sql += "'" + dict["club_id"] + "',";
                        sql += "'" + dict["clubcode"] + "',";
                        sql += toNull(dict["dailysno"]) + ",";
                        sql += toNull(dict["depositall"]) + ",";
                        sql += toNull(dict["discountpercent"]) + ",";
                        sql += toNull(dict["discounttotal"]) + ",";
                        sql += toNull(dict["dzxh"]) + ",";
                        sql += "'" + dict["endtime"] + "',";
                        sql += "'" + dict["f_paykind"] + "',";
                        sql += "'" + dict["fbillnohbaccno"] + "',";
                        sql += "'" + dict["fcditemno"] + "',";
                        sql += "'" + dict["fclub"] + "',";
                        sql += toNull(dict["fcount_hh"]) + ",";
                        sql += toNull(dict["fcount_mm"]) + ",";
                        sql += "'" + dict["fcreatedate"] + "',";
                        sql += "'" + dict["fcusttdno"] + "',";
                        sql += "'" + dict["fEntityNo"] + "',";
                        sql += toNull(dict["fhbbillflash"]) + ",";
                        sql += toNull(dict["finmpyj"]) + ",";
                        sql += "'" + dict["fmodifydate"] + "',";
                        sql += "'" + dict["Fpcno"] + "',";
                        sql += "'" + dict["fRemark"] + "',";
                        sql += "'" + dict["fRemarkdoc"] + "',";
                        sql += "'" + dict["fUserNo"] + "',";
                        sql += "'" + dict["fydbillno"] + "',";
                        sql += toNull(dict["generateflag"]) + ",";
                        sql += "'" + dict["grand_billcode"] + "',";
                        sql += toNull(dict["gratuitypercent"]) + ",";
                        sql += toNull(dict["gratuitytotal"]) + ",";
                        sql += "'" + dict["guest_identity"] + "',";
                        sql += "'" + dict["ifdown"] + "',";
                        sql += toNull(dict["invoiceflag"]) + ",";
                        sql += "'" + dict["invoiceno"] + "',";
                        sql += toNull(dict["is_check"]) + ",";
                        sql += "'" + dict["keyno"] + "',";
                        sql += toNull(dict["lockstatus"]) + ",";
                        sql += toNull(dict["memid"]) + ",";
                        sql += "'" + dict["memno"] + "',";
                        sql += "'" + dict["memsid"] + "',";
                        sql += "'" + dict["modify"] + "',";
                        sql += "'" + dict["modifytime"] + "',";
                        sql += toNull(dict["n_last"]) + ",";
                        sql += "'" + dict["name"] + "',";
                        sql += toNull(dict["noofguest"]) + ",";
                        sql += "'" + dict["opentime"] + "',";
                        sql += "'" + dict["openuserid"] + "',";
                        sql += toNull(dict["otherstatus"]) + ",";
                        sql += "'" + dict["parentshop"] + "',";
                        sql += toNull(dict["pay_status"]) + ",";
                        sql += "'" + dict["paycode"] + "',";
                        sql += "'" + dict["paydesp"] + "',";
                        sql += toNull(dict["payflag"]) + ",";
                        sql += "'" + dict["paymethod"] + "',";
                        sql += "'" + dict["payshop"] + "',";
                        sql += "'" + dict["periodno"] + "',";
                        sql += toNull(dict["printno"]) + ",";
                        sql += toNull(dict["quitydje"]) + ",";
                        sql += toNull(dict["rebatetotal"]) + ",";
                        sql += toNull(dict["rec_status"]) + ",";
                        sql += "'" + dict["reception"] + "',";
                        sql += "'" + dict["rq_check"] + "',";
                        sql += "'" + dict["saleid"] + "',";
                        sql += "'" + dict["saleshop"] + "',";
                        sql += toNull(dict["saletype"]) + ",";
                        sql += toNull(dict["sequence"]) + ",";
                        sql += "'" + dict["serverno"] + "',";
                        sql += "'" + dict["sex"] + "',";
                        sql += "'" + dict["shiftno"] + "',";
                        sql += "'" + dict["sttime"] + "',";
                        sql += "'" + dict["syscode"] + "',";
                        sql += "'" + dict["tableno"] + "',";
                        sql += "'" + dict["tableno_ext"] + "',";
                        sql += toNull(dict["taxpercent"]) + ",";
                        sql += toNull(dict["taxtotal"]) + ",";
                        sql += toNull(dict["tipstotal"]) + ",";
                        sql += toNull(dict["totalpayable"]) + ",";
                        sql += toNull(dict["ydallje"]) + ",";
                        sql += "'" + dict["zb_bm_ck"] + "')";

                    }
                    else if (Convert.ToInt32(dict["sync_type"]) == 1)
                    {

                    }
                    else if (Convert.ToInt32(dict["sync_type"]) == 2)
                    {

                    }
                    //sql = builder.ToString();
                    if (exec_sql(sql) > 0)
                    {
                        returnDict["sync_id"] = dict["sync_id"];
                        returnDict["status"] = 1;
                        exec_sql("insert into t_sync(sync_id,fdate) values('" + dict["sync_id"] + "','" + DateTime.Now + "')");

                    }
                    else
                    {
                        saveErrLog("pos_bills：执行sql出错,sync_id:" + dict["sync_id"] + "；" + sql + "; 返回0条记录。", DateTime.Now.ToString("yyyy-MM-dd") + "-sql_err");
                        returnDict["sync_id"] = dict["sync_id"];
                        returnDict["status"] = -1;
                        returnDict["remark"] = "这个sync_id处理失败了，请查看下sql_err.txt";
                    }
                }
                catch (Exception ex)
                {

                    saveErrLog(ex.Message + "\r\n" + ex.StackTrace.ToString(), "ex");
                    returnDict["sync_id"] = dict["sync_id"];
                    returnDict["status"] = -1;
                    returnDict["remark"] = "这个sync_id处理失败了，请查看下ex.txt";
                }
                finally
                {

                }
                return returnDict;
            }
            #endregion

            #region //处理账单从表的方法

            /// <summary>
            /// 处理账单从表的方法
            /// </summary>
            /// <param name="dict"></param>
            /// <returns></returns>
            public static Dictionary<string, Object> handle_pos_sales(Dictionary<string, Object> dict)
            {
                Dictionary<string, Object> returnDict = new Dictionary<string, Object>();
                //TODO: 下面要补上数据库操作的代码

                string sql = "";
                try
                {

                    if (ifSync_idExist("select COUNT(*) from t_sync where sync_id='" + dict["sync_id"] + "'") > 0)
                    {
                        returnDict["sync_id"] = dict["sync_id"];
                        returnDict["status"] = 1;
                        return returnDict;
                    }

                    if (Convert.ToInt32(dict["sync_type"]) == 0)
                    {
                        sql += "insert into pos_sales(acc_clubkinds1,acc_clubkinds2,acc_clubkinds3,accuserid,autocdflag,billcode,billshop,bm_ck,ch_printflag,checkin_id,closedate,closemethod,club_id,clubcode,complimentary_flag,deposit,disccode,discountpercent,discounttotal,dj_cb,dzxh,endtime,fbillNosub,fcditemno,fclub,fcount_hh,fcount_mm,fcreatedate,fcusttdno,fdayandhousr,fEntityNo,fit_paymentid,fit_saleid,fmodifydate,Fmp_m_id,fmpdaycount,Fpcno,Fremark,fUserNo,grand_billcode,gratuitypercent,gratuitytotal,holidaymethod,if_discount,if_generate,if_gratuity,if_import,if_invoice,if_other,if_revenue,if_tax,ifdown,is_addtion,is_backup,is_check,is_inv,is_meal,itemcode,itemid,itemname1,itemname2,itemspec,je_cb,keyno,kitchen_type,meal_id,meal_type,memno,modifier,modifier_memo,n_last,orderno,otherflag,otherid,parent_category,parent_kinds,parent_special,pay_status,paydate,payflag,paymentid,paymethod,payshop,pricemethod,printno,produceshop,quantity,reason,rebatetotal,rec_status,sale_category,sale_kinds,sale_prop,sale_special,sale_status,sale_type,saledate,saleid,saleprice,saleshop,saletime,saletotal,saleweight,seat_no,seatno,serverno,spandhyacc,stat_code,stockprice,stockqty,sttime,taxpercent,taxtotal,totalpayable,userid,v_artno,walkcust_ftype,xh,zbcardno) ";
                        sql += " values(";
                        sql += "'" + dict["acc_clubkinds1"] + "',";
                        sql += "'" + dict["acc_clubkinds2"] + "',";
                        sql += "'" + dict["acc_clubkinds3"] + "',";
                        sql += "'" + dict["accuserid"] + "',";
                        sql += toNull(dict["autocdflag"]) + ",";
                        sql += "'" + dict["billcode"] + "123123',";
                        sql += "'" + dict["billshop"] + "',";
                        sql += "'" + dict["bm_ck"] + "',";
                        sql += toNull(dict["ch_printflag"]) + ",";
                        sql += "'" + dict["checkin_id"] + "',";
                        sql += "'" + dict["closedate"] + "',";
                        sql += "'" + dict["closemethod"] + "',";
                        sql += "'" + dict["club_id"] + "',";
                        sql += "'" + dict["clubcode"] + "',";
                        sql += "'" + dict["complimentary_flag"] + "',";
                        sql += toNull(dict["deposit"]) + ",";
                        sql += "'" + dict["disccode"] + "',";
                        sql += toNull(dict["discountpercent"]) + ",";
                        sql += toNull(dict["discounttotal"]) + ",";
                        sql += toNull(dict["dj_cb"]) + ",";
                        sql += toNull(dict["dzxh"]) + ",";
                        sql += "'" + dict["endtime"] + "',";
                        sql += "'" + dict["fbillNosub"] + "',";
                        sql += "'" + dict["fcditemno"] + "',";
                        sql += "'" + dict["fclub"] + "',";
                        sql += toNull(dict["fcount_hh"]) + ",";
                        sql += toNull(dict["fcount_mm"]) + ",";
                        sql += "'" + dict["fcreatedate"] + "',";
                        sql += "'" + dict["fcusttdno"] + "',";
                        sql += toNull(dict["fdayandhousr"]) + ",";
                        sql += "'" + dict["fEntityNo"] + "',";
                        sql += "'" + dict["fit_paymentid"] + "',";
                        sql += "'" + dict["fit_saleid"] + "',";
                        sql += "'" + dict["fmodifydate"] + "',";
                        sql += "'" + dict["Fmp_m_id"] + "',";
                        sql += toNull(dict["fmpdaycount"]) + ",";
                        sql += "'" + dict["Fpcno"] + "',";
                        sql += "'" + dict["Fremark"] + "',";
                        sql += "'" + dict["fUserNo"] + "',";
                        sql += "'" + dict["grand_billcode"] + "',";
                        sql += toNull(dict["gratuitypercent"]) + ",";
                        sql += toNull(dict["gratuitytotal"]) + ",";
                        sql += toNull(dict["holidaymethod"]) + ",";
                        sql += toNull(dict["if_discount"]) + ",";
                        sql += toNull(dict["if_generate"]) + ",";
                        sql += toNull(dict["if_gratuity"]) + ",";
                        sql += toNull(dict["if_import"]) + ",";
                        sql += toNull(dict["if_invoice"]) + ",";
                        sql += toNull(dict["if_other"]) + ",";
                        sql += toNull(dict["if_revenue"]) + ",";
                        sql += toNull(dict["if_tax"]) + ",";
                        sql += "'" + dict["ifdown"] + "',";
                        sql += "'" + dict["is_addtion"] + "',";
                        sql += "'" + dict["is_backup"] + "',";
                        sql += toNull(dict["is_check"]) + ",";
                        sql += "'" + dict["is_inv"] + "',";
                        sql += "'" + dict["is_meal"] + "',";
                        sql += "'" + dict["itemcode"] + "',";
                        sql += toNull(dict["itemid"]) + ",";
                        sql += "'" + dict["itemname1"] + "',";
                        sql += "'" + dict["itemname2"] + "',";
                        sql += "'" + dict["itemspec"] + "',";
                        sql += toNull(dict["je_cb"]) + ",";
                        sql += "'" + dict["keyno"] + "',";
                        sql += "'" + dict["kitchen_type"] + "',";
                        sql += toNull(dict["meal_id"]) + ",";
                        sql += "'" + dict["meal_type"] + "',";
                        sql += "'" + dict["memno"] + "',";
                        sql += "'" + dict["modifier"] + "',";
                        sql += "'" + dict["modifier_memo"] + "',";
                        sql += toNull(dict["n_last"]) + ",";
                        sql += toNull(dict["orderno"]) + ",";
                        sql += toNull(dict["otherflag"]) + ",";
                        sql += toNull(dict["otherid"]) + ",";
                        sql += "'" + dict["parent_category"] + "',";
                        sql += "'" + dict["parent_kinds"] + "',";
                        sql += "'" + dict["parent_special"] + "',";
                        sql += toNull(dict["pay_status"]) + ",";
                        sql += "'" + dict["paydate"] + "',";
                        sql += toNull(dict["payflag"]) + ",";
                        sql += toNull(dict["paymentid"]) + ",";
                        sql += "'" + dict["paymethod"] + "',";
                        sql += "'" + dict["payshop"] + "',";
                        sql += toNull(dict["pricemethod"]) + ",";
                        sql += toNull(dict["printno"]) + ",";
                        sql += "'" + dict["produceshop"] + "',";
                        sql += toNull(dict["quantity"]) + ",";
                        sql += "'" + dict["reason"] + "',";
                        sql += toNull(dict["rebatetotal"]) + ",";
                        sql += toNull(dict["rec_status"]) + ",";
                        sql += "'" + dict["sale_category"] + "',";
                        sql += "'" + dict["sale_kinds"] + "',";
                        sql += toNull(dict["sale_prop"]) + ",";
                        sql += "'" + dict["sale_special"] + "',";
                        sql += toNull(dict["sale_status"]) + ",";
                        sql += toNull(dict["sale_type"]) + ",";
                        sql += "'" + dict["saledate"] + "',";
                        sql += toNull(dict["saleid"]) + "0001,";
                        sql += toNull(dict["saleprice"]) + ",";
                        sql += "'" + dict["saleshop"] + "',";
                        sql += "'" + dict["saletime"] + "',";
                        sql += toNull(dict["saletotal"]) + ",";
                        sql += toNull(dict["saleweight"]) + ",";
                        sql += toNull(dict["seat_no"]) + ",";
                        sql += "'" + dict["seatno"] + "',";
                        sql += "'" + dict["serverno"] + "',";
                        sql += "'" + dict["spandhyacc"] + "',";
                        sql += "'" + dict["stat_code"] + "',";
                        sql += toNull(dict["stockprice"]) + ",";
                        sql += toNull(dict["stockqty"]) + ",";
                        sql += "'" + dict["sttime"] + "',";
                        sql += toNull(dict["taxpercent"]) + ",";
                        sql += toNull(dict["taxtotal"]) + ",";
                        sql += toNull(dict["totalpayable"]) + ",";
                        sql += "'" + dict["userid"] + "',";
                        sql += "'" + dict["v_artno"] + "',";
                        sql += toNull(dict["walkcust_ftype"]) + ",";
                        sql += toNull(dict["xh"]) + ",";
                        sql += "'" + dict["zbcardno"] + "')";

                    }
                    if (Convert.ToInt32(dict["sync_type"]) == 1)
                    {
                        StringBuilder builder = new StringBuilder(400);
                        builder.Append("update gym_reserve set new_timestamp='").Append(dict["new_timestamp"]).Append("'");
                        if (dict.ContainsKey("time_mode"))
                        {
                            builder.Append(",time_mode='").Append(dict["time_mode"]).Append("'");
                        }
                        if (dict.ContainsKey("operator"))
                        {
                            builder.Append(",operator='").Append(dict["operator"]).Append("'");
                        }


                        if (dict.ContainsKey("status"))
                        {
                            if (dict["status"].ToString() == "9")
                            {
                                builder.Append(",color=8421631");
                            }
                        }
                        builder.Append(" where sid=").Append(dict["sid"]);
                        //builder.Append(" and new_timestamp='").Append(dict["timestamp"]).Append("'");
                        //sql = builder.ToString();
                    }
                    if (exec_sql(sql) > 0)
                    {
                        //这里暂时hardcode返回1成功标志
                        returnDict["sync_id"] = dict["sync_id"];
                        returnDict["status"] = 1;
                        exec_sql("insert into t_sync(sync_id,fdate) values('" + dict["sync_id"] + "','" + DateTime.Now + "')");
                    }
                    else
                    {
                        saveErrLog("pos_sales：执行sql出错，sync_id：" + dict["sync_id"] + "；" + sql + "; 返回0条记录。", DateTime.Now.ToString("yyyy-MM-dd") + "-sql_err");
                        returnDict["sync_id"] = dict["sync_id"];
                        returnDict["status"] = -1;

                    }
                }
                catch (Exception ex)
                {
                    // MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace.ToString());
                    saveErrLog("\r\n" + ex.Message + "\r\n" + ex.StackTrace.ToString(), "ex");
                    returnDict["sync_id"] = dict["sync_id"];
                    returnDict["status"] = -1;

                }
                return returnDict;
            }
            #endregion


            #region "声明变量"

            /// <summary>
            /// 写入INI文件
            /// </summary>
            /// <param name="section">节点名称[如[TypeName]]</param>
            /// <param name="key">键</param>
            /// <param name="val">值</param>
            /// <param name="filepath">文件路径</param>
            /// <returns></returns>
            [System.Runtime.InteropServices.DllImport("kernel32")]
            private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
            /// <summary>
            /// 读取INI文件
            /// </summary>
            /// <param name="section">节点名称</param>
            /// <param name="key">键</param>
            /// <param name="def">值</param>
            /// <param name="retval">stringbulider对象</param>
            /// <param name="size">字节大小</param>
            /// <param name="filePath">文件路径</param>
            /// <returns></returns>
            [DllImport("kernel32")]
            private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);

            private static string strFilePath = Application.StartupPath + "\\lxerp.ini";//获取INI文件路径
            private static string strSec = ""; //INI文件名

            #endregion

            #region "自定义读取INI文件中的内容方法"
            /// <summary>
            /// 自定义读取INI文件中的内容方法
            /// </summary>
            /// <param name="Section">键</param>
            /// <param name="key">值</param>
            /// <returns></returns>
            private static string ContentValue(string Section, string key)
            {

                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, key, "", temp, 1024, strFilePath);
                return temp.ToString();
            }
            #endregion

            #region "获取sqlconn连接参数"

            private static string sqlconn;

            public static string Sqlconn
            {
                get { return sqlconn; }
                set { sqlconn = value; }
            }

            public static void getsqlconn()
            {
                if (File.Exists(strFilePath))//读取时先要判读INI文件是否存在
                {

                    //strSec = Path.GetFileNameWithoutExtension(strFilePath);
                    strSec = "Connection";
                    string Database = ContentValue(strSec, "Database");
                    string ServerName = ContentValue(strSec, "ServerName");
                    string LogId = ContentValue(strSec, "LogId");
                    string Logpass = ContentValue(strSec, "Logpass");
                    sqlconn = @"server=" + ServerName + ";database = " + Database + "; uid =" + LogId + "; pwd = " + Logpass + ";";
                }
            }
            #endregion

            private static string ip;

            public static string Ip
            {
                get { return DbHelper.ip; }
                set { DbHelper.ip = value; }
            }
            private static string port;

            public static string Port
            {
                get { return DbHelper.port; }
                set { DbHelper.port = value; }
            }
            private static string dir;

            public static string Dir
            {
                get { return DbHelper.dir; }
                set { DbHelper.dir = value; }
            }
            private static string second;

            public static string Second
            {
                get { return DbHelper.second; }
                set { DbHelper.second = value; }
            }

            private static string socketport;

            public static string Socketport
            {
                get { return DbHelper.socketport; }
                set { DbHelper.socketport = value; }
            }

            private static string protocol;

            public static string Protocol
            {
                get { return DbHelper.protocol; }
                set { DbHelper.protocol = value; }
            }
            private static string domain;

            public static string Domain
            {
                get { return DbHelper.domain; }
                set { DbHelper.domain = value; }
            }
            #region //获取lxerp.ini文件里面的ip、端口号、服务路径
            public static void getIp()
            {
                try
                {
                    if (File.Exists(strFilePath))//读取时先要判读INI文件是否存在
                    {
                        strSec = "ADMIN";
                        ip = ContentValue(strSec, "ip");
                        port = ContentValue(strSec, "port");
                        dir = ContentValue(strSec, "dir");
                        second = ContentValue(strSec, "second");
                        socketport = ContentValue(strSec, "socketport");
                        protocol = ContentValue(strSec, "protocol");
                        domain = ContentValue(strSec, "domain");
                        //MessageBox.Show("http://" + ip + ":" + port + dir + "/api/sync/syncFromEts?");
                    }
                    else
                    {
                        //MessageBox.Show("lxerp.ini文件不存在！");
                        saveErrLog("lxerp.ini文件不存在！\r\n", "ex");


                    }
                }
                catch (Exception ex)
                {
                    saveErrLog("获取配置文件参数失败!\r\n请检查lxerp.ini文件ADMIN组下是否有ip、port、dir、second、socketport、protocol、domain等值！\r\n" + ex.Message + "\r\n" + ex.StackTrace.ToString(), "ex");
                    //MessageBox.Show("请检查lxerp.ini文件ADMIN组下是否有ip、port、dir、second、socketport、protocol、domain等值！\n\r" + ex.Message, "获取配置文件参数失败");
                }

            }
            #endregion

            private static string fclub;

            public static string Fclub
            {
                get { return DbHelper.fclub; }
                set { DbHelper.fclub = value; }
            }

            private static string gymid;

            public static string Gymid
            {
                get { return DbHelper.gymid; }
                set { DbHelper.gymid = value; }
            }
            private static string ver;

            public static string Ver
            {
                get { return DbHelper.ver; }
                set { DbHelper.ver = value; }
            }

            //数据库是否存在延迟发送的两个字段
            private static bool hasDelayField;

            public static bool HasDelayField
            {
                get { return DbHelper.hasDelayField; }
                set { DbHelper.hasDelayField = value; }
            }
            //BG_JSON发送次数
            private static int sendCounts;

            public static int SendCounts
            {
                get { return sendCounts; }
                set { sendCounts = value; }
            }


            #region //获取lxerp.ini文件里面的ip、端口号、服务路径
            public static void getFclub()
            {
                try
                {
                    if (File.Exists(strFilePath))//读取时先要判读INI文件是否存在
                    {
                        strSec = "pcidno";
                        fclub = ContentValue(strSec, "subclub");

                    }
                    else
                    {
                        //MessageBox.Show("lxerp.ini文件不存在！");
                        DbHelper.saveErrLog("lxerp.ini文件不存在！", "ex");

                    }
                }
                catch (Exception ex)
                {

                    saveErrLog("请检查lxerp.ini文件下pcidno组是否有subclub值!\n\r" + ex.Message + "\n\r" + ex.StackTrace, "ex");
                    //MessageBox.Show("请检查lxerp.ini文件下pcidno组是否有subclub值!\n\r" + ex.Message, "获取配置文件参数失败");

                }

            }
            #endregion

            #region //根据传入的sql语句返回受影响的行数
            /// <summary>
            /// 根据传入的sql语句返回受影响的行数
            /// </summary>
            /// <param name="sql"></param>
            /// <returns></returns>
            public static int exec_sql(string sql)
            {
                int result = 0;
                SqlConnection conn = new SqlConnection(Sqlconn);
                try
                {
                    if (sql.Contains("mem_member"))
                    {
                        saveErrLog(sql, DateTime.Now.ToString("yyyy-MM-dd") + "-sql");
                    }
                    if (sql.Contains("gym_reserve"))
                    {
                        saveErrLog(sql, DateTime.Now.ToString("yyyy-MM-dd") + "-sql");
                    }
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.CommandTimeout = 50000;
                    conn.Open();

                    //SqlCommand cmd1 = new SqlCommand("select Context_Info() ", conn);
                    //reader = cmd1.ExecuteReader();

                    SqlCommand cmd2 = new SqlCommand("set Context_Info 0x123456789", conn);

                    //不会有返回行
                    if (cmd2.ExecuteNonQuery() > 0)
                    {
                        saveErrLog("set Context_Info 0x123456789", "log");
                    }


                    result = cmd.ExecuteNonQuery();

                    //SqlCommand cmd3 = new SqlCommand("set Context_Info " + contextInfo, conn);
                    //cmd3.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    saveErrLog(sql + ex.Message, DateTime.Now.ToString("yyyy-MM-dd") + "-sql_err");
                    return result;
                }

                finally
                {
                    conn.Close();
                }

                return result;
            }
            #endregion

            #region //判断错误的sync_id是否在sync表存在
            /// <summary>
            /// 判断错误的sync_id是否在sync表存在
            /// </summary>
            /// <param name="sql"></param>
            /// <returns></returns>
            public static int ifSync_idExist(string sql)
            {
                int result = 0;
                SqlConnection conn = new SqlConnection(Sqlconn);
                try
                {


                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.CommandTimeout = 50000;
                    conn.Open();
                    result = int.Parse(cmd.ExecuteScalar().ToString());
                    //MessageBox.Show(result.ToString());
                }
                catch (Exception ex)
                {
                    saveErrLog(sql + ex.Message, DateTime.Now.ToString("yyyy-MM-dd") + "-sql_err");
                    return result;
                }

                finally
                {
                    conn.Close();

                }

                return result;
            }
            #endregion

            //加一把锁
            public static object locker = new object();

            #region //保存执行错误的sql
            public static void saveErrLog(string log, string txtName)
            {

                lock (locker)
                {
                    log = DateTime.Now.ToString() + " : " + log;
                    if (File.Exists(Application.StartupPath + "\\" + txtName + ".txt"))
                    {
                        StreamWriter SW;
                        SW = File.AppendText("" + txtName + ".txt");
                        SW.WriteLine(log + "\r\n");
                        SW.Close();

                    }
                    else
                    {
                        StreamWriter SW;
                        SW = File.CreateText("" + txtName + ".txt");
                        SW.WriteLine(log + "\r\n");
                        SW.Close();

                    }
                }
            }
            #endregion

        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            //if (myThread != null)
            //{
            //    myThread.Abort();
            //}
            //try
            //{
            //    this.socket.Shutdown(SocketShutdown.Both);
            //}
            //catch (Exception ex)
            //{
            //    DbHelper.saveErrLog(ex.Message + "\r\n" + ex.StackTrace.ToString(), "ex");
            //}

            //this.socket.Close();
            Application.ExitThread();
        }
    }

}

